
#include "ScriptSystem.h"
#include <ALittleClient/LogSystem/LogSystem.h>

namespace ALittle
{

ScriptSystem& ScriptSystem::Instance()
{
	static ScriptSystem instance;
	return instance;
}
void ScriptSystem::Setup() { Reset(); }

void ScriptSystem::Shutdown() { Clear(); }

ScriptSystem::ScriptSystem() : m_L(0) { }
ScriptSystem::~ScriptSystem() { ScriptSystem::Instance().Shutdown(); }

void ScriptSystem::Reset()
{
	if (m_L) { ::lua_close(m_L); m_L = NULL; }

	m_L = ::luaL_newstate();
	if (!m_L)
	{
		ALITTLE_ERROR("lua_open failed!");
		return;
	}
	LuaTinker::init(m_L);

	::luaL_openlibs(m_L);

	g_ScriptSystem.RegisterClass2Script<ScriptSystem>("SailScriptSystem")
		.AddMemberFunction("GarbageCollection", &ScriptSystem::GarbageCollection);

	g_ScriptSystem.SetValue("Sail_ScriptSystem", &g_ScriptSystem);
}

void ScriptSystem::Clear()
{
	if (m_L) { ::lua_close(m_L); m_L = NULL; }
}

void ScriptSystem::RunScript(const std::string& scriptContent)
{
	LuaTinker::dostring(m_L, scriptContent.c_str());
}

void ScriptSystem::RunScriptFile(const std::string& scriptFileName)
{
	LuaTinker::dofile(m_L, scriptFileName.c_str());
}

void ScriptSystem::GarbageCollection()
{
	if (m_L)
	{
		ALITTLE_INFO("Garbage Collection");
		if (::lua_gc(m_L, LUA_GCCOLLECT, 0))
			LuaTinker::print_error(m_L, lua_tostring(m_L, -1));
	}
}

} // Sail
